$(function () {
  // 巡更 点位管理 显示
  $(".patrollingPointBtn").on("click", function (event) {
    event.preventDefault();
    $(".patrollingPoint-pop").addClass("is-visible3");
    var n = 1;
    $('#patrollingPointPageBox .pageJump input').val('');
    $('#patrollingPointModal .searchInputStyle').val('');
    $('#patrollingPointSelectAll').prop('checked',false);
    patrollingPointPageList(n);
  });
  //创建二维码
  function createQRCode(id, url, width, height, src) {
    $('#' + id).empty();
    jQuery('#' + id).qrcode({
      render: 'canvas',
      text: url,
      width : width,              //二维码的宽度  
      height : height,            //二维码的高度  
      imgWidth : width/4,         //图片宽
      imgHeight : height/4,       //图片高
      src: src            //图片中央的二维码
    });
  }
  // 添加二维码
  var adduuid;
  function codeInit() {
    adduuid = (new Date()).valueOf();
    adduuid = adduuid.toString();
    createQRCode("qrcode", adduuid, 180, 180, "img/logo.png");
  }

  $('#saveQrCode').click(function(){
    var canvas = $('#qrcode').find("canvas").get(0);
  try {//解决IE转base64时缓存不足，canvas转blob下载
    var blob = canvas.msToBlob();
    navigator.msSaveBlob(blob, 'qrcode.jpg');
  } catch (e) {//如果为其他浏览器，使用base64转码下载
    var url = canvas.toDataURL('image/jpeg');
    $("#download").attr('href', url).get(0).click();
  }
    return false;
  });

  // 点击 添加按钮 
  $("#patrollingPointAddBtn").on("click", function (event) {
    event.preventDefault();
    console.log("添加页面");
    $(".patrollingPointAddPage-pop").addClass("is-visible3");
    // 添加二维码
    codeInit();
    $("#patrollingPointAddPage .qRCodeValue").val(adduuid);
    // 获取所有组织
    var getOrganizationListRet = getOrganizationList();
    getOrganizationListRet.then(function (data) {
      console.log(data);
      $('#patrollingPointAddPage .patrollingPointAddPageOragList').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#patrollingPointAddPage .patrollingPointAddPageOragList').append('<option value="' + data.data[i].id + '" selected>' + data.data[i].orgName + '</option>')
      }
    }).catch(function (err) {
      console.log(err);
    });
  });
  // 添加页面 关闭
  $(".patrollingPointAddPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close1") ||
      $(event.target).is(".patrollingPointAddPage-pop")
    ) {
      event.preventDefault();
      //Modal验证销毁重构
      $("#patrollingPointAddPage").data('bootstrapValidator').destroy();
      $('#patrollingPointAddPage').data('bootstrapValidator', null);
      addPatrollingPointAddPage();
      $("#patrollingPointAddPage input").val('');      
      $(this).removeClass("is-visible3");
    }
  });

  // 添加 点位管理 
  // var multipartFile;
  // var file;
  // $("#multipartFile").on("change", function(e){
  //   console.log(this)
  //   file = this.files[0];
  //   console.log(file);
  //   formData = new FormData();
  //   formData.append("multipartFile", file);
  //   console.log(formData);
  // })
  // console.log(multipartFile);
  // 添加点位管理提交
  addPatrollingPointAddPage();
  function addPatrollingPointAddPage() {
    $("#patrollingPointAddPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        name: {
          validators: {
            notEmpty: {
              message: '点位名称不能为空'
            }
          }
        },
        address: {
          validators: {
            notEmpty: {
              message: '地址不能为空'
            }
          }
        },
        latitude: {
          validators: {
            notEmpty: {
              message: '经度不能为空'
            }
          }
        },
        longitude: {
          validators: {
            notEmpty: {
              message: '纬度不能为空'
            }
          }
        },
        orgId: {
          validators: {
            notEmpty: {
              message: '所属组织不能为空'
            }
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();      
      //  点击提交 提交图片到数据库
      var canvas = $("#patrollingPointAddPage").find("canvas").get(0);
      var src = canvas.toDataURL("image/jpg");
      $("#hideImg").val(src.substr(22));
      var name = $('#patrollingPointAddPage .patrollingPointAddPageName input').val();
      var address = $('#patrollingPointAddPage .patrollingPointAddPageAddress input').val();
      var latitude = $('#patrollingPointAddPage .patrollingPointAddPageLatitudes input').val();
      var longitude = $('#patrollingPointAddPage .patrollingPointAddPageLongitude input').val();
      var patrollingPointAddPageOrag = $('#patrollingPointAddPage .patrollingPointAddPageOrag input').val();
      var devCode = 1;
    
      // 提交表单
      var $form = $(e.target);
      var obj = $form.serializeObject();
      var orgId = $("#patrollingPointAddPage .patrollingPointAddPageOragList-pop").val();
      console.log(obj);
      var ret = getPatrollingSave(orgId, JSON.stringify(obj));
      ret.then(function (data) {
        console.log(data);
        // 添加后更新地图点位
        devCode = data.data.id;
        scoketKeepMapShowFunc('keepWatch',name , devCode, address, longitude, latitude);
      
        $('.patrollingPointAddPage-pop').removeClass('is-visible3');
        //Modal验证销毁重构
        $("#patrollingPointAddPage").data('bootstrapValidator').destroy();
        $('#patrollingPointAddPage').data('bootstrapValidator', null);
        addPatrollingPointAddPage();
        $('#patrollingPointAddPage input').val('');
        patrollingPointPageList(patrollingPointPageNumCurr);
        tipModalFunc('添加成功!');
      }).catch(function (err) {
        console.log(err);
      });

      // 点击提交 提交图片到数据库
      // var canvas = $("#patrollingPointAddPage").find("canvas").get(0);
      // console.log(canvas);
      // var src = canvas.toDataURL("image/jpg");
      // console.log(src);
      // console.log(src.substr(22));
      // var multipartFile = src.substr(22);
      // var formData = new FormData();

      // function dataURItoBlob(dataURI) {//图片转成Buffer    
      //   var byteString = atob(dataURI.split(',')[1]);
      //   var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      //   var ab = new ArrayBuffer(byteString.length);
      //   var ia = new Uint8Array(ab);
      //   for (var i = 0; i < byteString.length; i++) {
      //       ia[i] = byteString.charCodeAt(i);
      //   }
      //   return new Blob([ab], {type: mimeString});
      // }
      // var multipartFile = dataURItoBlob(src);
      // console.log(multipartFile);
      // formData.append('source_from','webpage_upload');
      // formData.append("multipartFile", multipartFile);

      // var orgId = $("#patrollingPointAddPage .patrollingPointAddPageOragList-pop").val();
      // $.ajax({
      //   url: " /patrol/points/orgid="+ orgId,
      //   type: 'post',
      //   data: formData,
      //   contentType: false,
      //   processData: false,
      //   success: function (res) {
      //     console.log(res);
      //     formData = {};
      //   },
      //   error: function (res) {
      //     console.log(res);
      //   }
      // });
    })
  }

  // 添加页面 取消按钮
  $("#patrollingPointAddPage .patrollingPointAddPageBtnCancel").on("click", function () {
    $("#patrollingPointAddPage input").val('');
    //Modal验证销毁重构
    $("#patrollingPointAddPage").data('bootstrapValidator').destroy();
    $('#patrollingPointAddPage').data('bootstrapValidator', null);
    $(".patrollingPointAddPage-pop").removeClass("is-visible3");
  })

  // 修改页面 取消按钮
  $("#patrollingPointModifyPage .patrollingPointAddPageBtnCancel").on("click", function () {
    $("#patrollingPointModifyPage input").val('');
    //Modal验证销毁重构
    $("#patrollingPointAddPage").data('bootstrapValidator').destroy();
    $('#patrollingPointAddPage').data('bootstrapValidator', null);
    $(".patrollingPointModifyPage").removeClass("is-visible3");
  })

  //设备管理  分页功能
  var patrollingPointPageNum = 1;
  var patrollingPointPageNumCurr = 1;

  function patrollingPageFunc(pageSum, startPageNum) {
    console.log(pageSum);
    if (pageSum <= 1) {
      $('#patrollingPointPageBox .pageJump').hide()
    } else {
      $('#patrollingPointPageBox .pageJump').show()
    }
    Page({
      num: pageSum, //页码数
      startnum: startPageNum, //指定页码
      elem: $('#patrollingPage'), //指定的元素
      callback: function (n) { //回调函数
        patrollingPointPageNumCurr = n;
        // $('#earlyWarningPageBox .pageJump').show();
        patrollingPointPageList(n);
        // 当翻到下一页时 清除掉 全选按钮的 选中状态
        $("#patrollingPointSelectAll").prop("checked", false);
      }
    });
  };

  // 渲染 巡更点位 的列表
  function patrollingPointPageList(n) {
    var obj = {};
    obj.size = 10;
    obj.page = n - 1;
    var ret = getPatrollingInfo(obj);
    ret.then(function (data) {
      console.log(data);
      var content = data.data.content;
      patrollingPointPageNum = data.data.totalPages;
      size = data.data.size;
      console.log(patrollingPointPageNum);
      $('#patrollingPointModal .tbodyList').html('');
      for (var i = 0; i < content.length; i++) {
        $('#patrollingPointModal .tbodyList').append('<tr><td><input type="checkbox" class="check" devid="' + content[i].id + '"></td><td>' + ((n - 1) * size + i + 1) + '</td><td>' + content[i].name + '</td><td>' + content[i].address + '</td><td><span class="seeDetailsStyle" id=' + content[i].id + ' detaileOrg=' + content[i].organization.orgName + ' latitude=' + content[i].latitude + ' longitude=' + content[i].longitude + ' qRCodeValue="'+content[i].qRCodeValue+'">查看详情</span><span class="modifyBtnStyle" modifyOrg=' + content[i].organization.id + ' id=' + content[i].id + ' latitude=' + content[i].latitude + ' longitude=' + content[i].longitude + ' qRCodeValue="'+content[i].qRCodeValue+'">修改</span></td></tr>');
      }
      patrollingPageFunc(patrollingPointPageNum, n);
    }).catch(function (err) {
      console.log(err);
    });
  }

  // 巡更 点位管理 关闭窗口
  $(".patrollingPoint-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".patrollingPoint-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
    }
  });
  // 小叉 关闭窗口    
  $('.patrollingPoint-pop .closeModal').on('click', function (event) {
    event.preventDefault();
    $('.patrollingPoint-pop').removeClass('is-visible3');
  });


  // 全选 反选
  // 设置 全选按钮的选中状态 allcheck
  $("#patrollingPointSelectAll").on("click", function () {
    var allcheck = $("#patrollingPointSelectAll").prop("checked");
    $("#patrollingPointModal .tbodyList .check").prop("checked", allcheck);
  });
  // 反选
  $("#patrollingPointModal .tbodyList").on("click", '.check', function () {
    var length1 = $("#patrollingPointModal .tbodyList").find(":checkbox").length;
    var length2 = $("#patrollingPointModal .tbodyList").find(":checked").length;
    if (length1 == length2) {
      $("#patrollingPointSelectAll").prop("checked", true);
    } else {
      $("#patrollingPointSelectAll").prop("checked", false);
    }
  });
  // 删除
  $("#patrollingDelBtn").on("click", function () {
    $("#patrollingPointModal .tbodyList").find(":checked").each(function (index, ele) {
      // 获取自定义属性的值 devid
      var id = $(this).attr("devid");
      var ret = delPatrollingInfo(id);
      ret.then(function (data) {
        console.log(data);
        // 删除地图点位
        tipModalFunc('删除成功!');
        scoketKeepMapDelFunc(id);
        patrollingPointPageList(patrollingPointPageNumCurr);
      }).catch(function (err) {
        console.log(err);
      });
    })
  });
  // 巡更点位查看详情，创建二维码
  $('#seepatrollingsaveQrCode').click(function(){
    var seename = $('#patrollingPointDetailsPage .patrollingPointAddPageName .name').val();
    var canvas = $('#seepatrollingqrcode').find("canvas").get(0);
  try {//解决IE转base64时缓存不足，canvas转blob下载
    var blob = canvas.msToBlob();
    navigator.msSaveBlob(blob, seename+'.jpg');
  } catch (e) {//如果为其他浏览器，使用base64转码下载
    var url = canvas.toDataURL('image/jpeg');
    $("#seepatrollingdownload").attr('href', url).get(0).click();
  }
    return false;
  });
  // 巡更点位管理 查看详情 显示页面
  
  $("#patrollingPointModal .tbodyList").on("click", '.seeDetailsStyle', function () {
    event.preventDefault();
    $(".patrollingPointDetailsPage-pop").addClass("is-visible3");
    var id = $(this).attr("id");
    console.log(id);
    // var ret = getpatrollingqrCode(id);
    // ret.then(function(data) {
    //   console.log(data);
    // }).catch(function (err) {
    //   console.log(err);
    // });
    // 填数据
    var name = $(this).parent().parent().find("td").eq(2).text();
    var address = $(this).parent().parent().find("td").eq(3).text();
    var org = $(this).attr("detaileOrg");
    var lati = $(this).attr("latitude");
    var longi = $(this).attr("longitude");
    var qRCodeValue = $(this).attr("qRCodeValue");
    $("#patrollingPointDetailsPage .pointName").val(name);
    $("#patrollingPointDetailsPage .pointAddress").val(address);
    $("#patrollingPointDetailsPage .pointOra").val(org);
    $("#patrollingPointDetailsPage .pointLatitudes").val(lati);
    $("#patrollingPointDetailsPage .pointLongitude").val(longi);
    // 二维码编码
    $("#patrollingPointDetailsPage .qRCodeValue").val(qRCodeValue);
    createQRCode("seepatrollingqrcode", qRCodeValue, 180, 180, "img/logo.png");
  });
  // 查看详情 关闭页面
  $(".patrollingPointDetailsPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close") ||
      $(event.target).is(".patrollingPointDetailsPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
    }
  });
  // 巡更点位管理 修改页面
  var modId;
  $("#patrollingPointModal .tbodyList").on("click", '.modifyBtnStyle', function () {
    event.preventDefault();
    $(".patrollingPointModifyPage-pop").addClass("is-visible3");
    var name = $(this).parent().parent().find("td").eq(2).text();
    var address = $(this).parent().parent().find("td").eq(3).text();
    var org = $(this).attr("modifyOrg");
    var lati = $(this).attr("latitude");
    var longi = $(this).attr("longitude");
    var qRCodeValue = $(this).attr('qRCodeValue');
    modId = $(this).attr("id");
    // console.log(org);
    $("#patrollingPointModifyPage .pointName").val(name);
    $("#patrollingPointModifyPage .pointAddress").val(address);
    $("#patrollingPointModifyPage .pointLatitudes").val(lati);
    $("#patrollingPointModifyPage .pointLongitude").val(longi);
    $("#patrollingPointModifyPage .qRCodeValue").val(qRCodeValue);
    // 获取所有组织
    var getOrganizationListRet = getOrganizationList();
    getOrganizationListRet.then(function (data) {
      $('#patrollingPointModifyPage .patrollingPointModifyPageOragList-pop').html('');
      for (var i = 0; i < data.data.length; i++) {
        $('#patrollingPointModifyPage .patrollingPointModifyPageOragList-pop').append('<option value="' + data.data[i].id + '">' + data.data[i].orgName + '</option>')
      }
      $("#patrollingPointModifyPage .patrollingPointModifyPageOragList-pop").val(org);
    }).catch(function (err) {
      console.log(err);
    });
    // 展示二维码
  createQRCode("editpatrollingqrcode", qRCodeValue, 180, 180, "img/logo.png");
  });
  // 修改 保存 提交
  function modiftyPatrollingPointPage() {
    $("#patrollingPointModifyPage").bootstrapValidator({
      message: 'This value is not valid',
      feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
      },
      fields: {
        name: {
          validators: {
            notEmpty: {
              message: '点位名称不能为空'
            }
          }
        },
        address: {
          validators: {
            notEmpty: {
              message: '地址不能为空'
            }
          }
        },
        latitude: {
          validators: {
            notEmpty: {
              message: '经度不能为空'
            }
          }
        },
        longitude: {
          validators: {
            notEmpty: {
              message: '纬度不能为空'
            }
          }
        },
        orgId: {
          validators: {
            notEmpty: {
              message: '所属组织不能为空'
            }
          }
        },
      }
    }).on("success.form.bv", function (e) {
      e.preventDefault();
      var $form = $(e.target);
      var obj = $form.serializeObject();
      // var id = $("#patrollingPointModal .modifyBtnStyle").attr("id");
      console.log(modId);
      obj.id = modId;
      console.log(obj);

      var name = $('#patrollingPointModifyPage .patrollingPointAddPageName input').val();
      var address = $('#patrollingPointModifyPage .patrollingPointAddPageAddress input').val();
      var latitude = $('#patrollingPointModifyPage .patrollingPointAddPageLatitudes input').val();
      var longitude = $('#patrollingPointModifyPage .patrollingPointAddPageLongitude input').val();
      var patrollingPointAddPageOrag = $('#patrollingPointModifyPage .patrollingPointAddPageOrag input').val();

      var orgId = $("#patrollingPointModifyPage .patrollingPointModifyPageOragList-pop").val();
      var ret = getPatrollingSave(orgId, JSON.stringify(obj));
      ret.then(function (data) {
        console.log(data);
        // 添加后更新地图点位

        scoketKeepMapShowFunc('keepWatch',name , modId, address, longitude, latitude);
      
        $('.patrollingPointModifyPage-pop').removeClass('is-visible3');
        //Modal验证销毁重构
        $("#patrollingPointModifyPage").data('bootstrapValidator').destroy();
        $('#patrollingPointModifyPage').data('bootstrapValidator', null);
        modiftyPatrollingPointPage();
        $('#patrollingPointModifyPage input').val('');
        patrollingPointPageList(patrollingPointPageNumCurr);
        tipModalFunc('修改成功!');
      }).catch(function (err) {
        console.log(err);
      })
    })
  }
  modiftyPatrollingPointPage();
  // 巡更点位管理 修改页面 关闭
  $(".patrollingPointModifyPage-pop").on("click", function (event) {
    if (
      $(event.target).is(".cd-popup-close1") ||
      $(event.target).is(".patrollingPointModifyPage-pop")
    ) {
      event.preventDefault();
      $(this).removeClass("is-visible3");
      $("#patrollingPointModifyPage").data('bootstrapValidator').destroy();
      $('#patrollingPointModifyPage').data('bootstrapValidator', null);
      modiftyPatrollingPointPage();
    }
  });
  // 点位管理模糊搜索 http://localhost:9092/patrol/getPatrolPoints?address=sdf
  searchFunc();
  function searchFunc() {
    
    //模糊查询
    $('body').on('click', function () {
      $("#patrollingPointModal .searchList").hide();
    });
    var fn = _.debounce(function () {
      $("#patrollingPointModal .searchList").show();
      // hide2border();
      if ($("#patrollingPointModal .searchList li")) { //键盘抬起后就判断页面中是否存在这个元素,存在就删除
        $("#patrollingPointModal .searchList li").remove();
      }
      var searchContent = $("#patrollingPointModal .devAddress").val();
      searchContent = $.trim(searchContent);
      console.log(searchContent)
      if (searchContent) {
        var address = 'address=' + searchContent;
      } else {
        var address = '';
        $("#patrollingPointModal .searchList").html('');
      }

      //查询内容存在则搜索
      if (searchContent) {
        $.ajax({
          url: "/patrol/getPatrolPoints?" + address,
          type: "GET",
          // async: false,
          success: function (result) {
            console.log(result)
            var data = result.data;
            if (data.length <= 10) {
              for (var i = 0; i < data.length; i++) {
                var address = data[i].address;
                $("#patrollingPointModal .searchList").append('<li>' + address + '</li>');
                // hide2border();
              }
            }
          }
        });
      }
      $("#patrollingPointModal .searchList").show();
    }, 500);
    $("#patrollingPointModal .devAddress").on("input", function (e) {
      fn();
    });
    //直接输入地址,点击列表查询
    $("#patrollingPointModal .searchList").on("click", "li", function () {
      $("#patrollingPointModal .searchList").show();
      var liVal = $(this).text();
      liVal = $.trim(liVal);
      var searchVal = $("#patrollingPointModal .devAddress").val(liVal);

      $("#patrollingPointModal .searchList").html(""); //hide
      return false;
    });
  }
  var patrollinClickSearchFn = _.debounce(function () {
    $.ajax({
      url: "/patrol/getPatrolPoints?" + address,
      type: "GET",
      // async: false,
      success: function (result) {
        console.log(result)
        var data = result.data;
        if (data.length <= 10) {
          for (var i = 0; i < data.length; i++) {
            var address = data[i].address;
            $("#patrollingPointModal .searchList").append('<li>' + address + '</li>');
            // hide2border();
          }
        }
      }
    });
  }, 500);
  // 点击点位管理搜索按钮
  $('#patrollingsearchBtn').on('click',function(){
    patrollinClickSearchFn();
  });


});
